package com.igeek.ch02.controller;

import com.igeek.ch02.common.CommonResult;
import com.igeek.ch02.entity.User;
import com.igeek.ch02.service.UserService;
import com.igeek.ch02.utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

@WebServlet(name = "UserLoginServlet" , urlPatterns = {"/login" , "/userLogin"})
public class UserLoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("UserLoginServlet doPost()");

        //1.设置请求的编码集
        //request.setCharacterEncoding("UTF-8");
        //设置响应的编码集
        //response.setContentType("application/json;charset=UTF-8");

        //2.收集表单数据  json格式
        Map<String, String> map = JSONUtils.transferObj(request);
        String name = map.get("name");
        String pwd = map.get("pwd");
        int expire = Integer.parseInt(map.get("expire"));
        //System.out.println("name = "+name +" , pwd = "+pwd +" , expire = "+expire);

        //从请求中获取所有Cookie，匹配判断
        String nameCookie = null;
        String pwdCookie = null;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie!=null){
                    //匹配判断是否存在姓名和密码，若存在则取出值
                    if(cookie.getName().equals("name")){
                        nameCookie = URLDecoder.decode(cookie.getValue() , "UTF-8");  //解码
                    }
                    if(cookie.getName().equals("pwd")){
                        pwdCookie = cookie.getValue();
                    }
                }
            }
        }

        if(name.equals("") && pwd.equals("") && nameCookie==null && pwdCookie==null){
            //若表单中没有数据，Cookie中也没有数据，则直接显示登录界面
            return;
        }else if(name.equals("") && pwd.equals("") && nameCookie!=null && pwdCookie!=null){
            //若表单中没有数据，但是Cookie中有数据，则直接赋值
            name = nameCookie;
            pwd = pwdCookie;
        }


        //3.执行业务业务逻辑
        CommonResult commonResult = null;
        if(name!=null && pwd!=null && !name.equals("") && !pwd.equals("")){
            User user = userService.login(name, pwd);
            if(user!=null){
                String state = user.getState();
                switch (state){
                    case "0":
                        commonResult = new CommonResult(455 , "尚未审核，请耐心等待");
                        break;
                    case "1":
                        //将登录成功的信息，且expire选择时长；添加至Cookie，响应到客户端浏览器中
                        if(expire>0){
                            //1.创建Cookie对象
                            Cookie usernameCookie = new Cookie("name", URLEncoder.encode(name , "UTF-8")); //编码
                            Cookie passwordCookie = new Cookie("pwd",pwd);

                            //2.设置有效期，保存在浏览器所在PC机上
                            usernameCookie.setMaxAge(expire*24*60*60);
                            passwordCookie.setMaxAge(expire*24*60*60);

                            //3.通过响应，将Cookie添加至浏览器中
                            response.addCookie(usernameCookie);
                            response.addCookie(passwordCookie);
                        }

                        //在会话作用域中存储登录成功者的信息
                        HttpSession session = request.getSession();
                        session.setAttribute("user" , user);

                        commonResult = new CommonResult(200 , "审核通过，登录成功" , user);
                        break;
                    case "2":
                        commonResult = new CommonResult(455 , "审核失败，登录失败");
                        break;
                }
            }else{
                commonResult = new CommonResult(455 , "姓名与密码不匹配");
            }
        }else{
            commonResult = new CommonResult(455 , "姓名和密码不能为空");
        }

        //4.响应json格式数据至浏览器
        JSONUtils.writeJson(response , commonResult);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
